import YAML from "yaml";

export async function getLatestDownloadUrl(path, isMac = false, isArm = false) {
  const baseUrl = "https://e3-store.oss-cn-hangzhou.aliyuncs.com/app";

  const response = await fetch(`${baseUrl}/${path}`);
  if (!response.ok) {
    console.log(response);
    return;
  }
  const yamlText = await response.text();
  const yamlData = YAML.parse(yamlText);

  if (yamlData && yamlData.files && yamlData.files.length > 0) {
    let urlToRedirect;
    if (isMac) {
      urlToRedirect = isArm
        ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
          yamlData.files.find((file) => file.url.includes("arm64"))?.url
        : // eslint-disable-next-line @typescript-eslint/no-explicit-any
          yamlData.files.find((file) => file.url.includes("x64"))?.url;
    } else {
      urlToRedirect = yamlData.path;
    }
    if (urlToRedirect) {
      return `${baseUrl}/${urlToRedirect}`;
    } else {
      console.error("No suitable URL found for redirection.");
    }
  } else {
    console.error("No valid data found in the YAML file.");
  }
}

// export async function getRedirectBasedOnOS(userAgent) {
//   const ua = UAParser(userAgent);
//   const isWindows = ua.os.is("Windows");
//   const isMac = ua.os.is("Mac OS");
//   const isArm = ua.cpu.is("arm64") || ua.cpu.is("arm");

//   const isSupported = isMac || isWindows;
//   const yamlUrl = isMac ? "latest-mac.yml" : "latest.yml";
//   const appUrl = await getLatestDownloadUrl(yamlUrl, isMac, isArm);
//   const rhinoPluginUrl = await getLatestDownloadUrl("latest-for-rh.yml");

//   return { appUrl, rhinoPluginUrl, isWindows, isArm };
// }
